import { CallLimitDetailInfo } from 'admin/schema/CorporateSet';
import { updateCallLimitDetail } from 'admin/servers/servers';
import { Form, InputNumber, message, Modal } from 'antd';
import React, { useState } from 'react';
import { checkAllowableTimes } from './CheckAllowableTimes';

type Props = {
  visible: boolean;
  callLimitDetail: CallLimitDetailInfo;
  successFn: Function;
  cancelFn: Function;
};

/**弹窗-限制频次 */
export const DetailModal: React.FC<Props> = ({
  visible,
  callLimitDetail: {
    dayAllowableTimes,
    weekAllowableTimes,
    monthAllowableTimes,
    halfYearAllowableTimes,
  },
  successFn,
  cancelFn,
}) => {
  const [form] = Form.useForm();
  const [confirmLoading, setConfirmLoading] = useState(false);
  const handleOK = () => {
    form.submit();
  };
  const handleCancel = () => {
    form.resetFields();
    cancelFn();
  };
  /**
   *
   * @param a 天
   * @param b 周
   * @param c 1个月
   * @param d 6个月
   * @returns 是否通过检测
   */

  /**
   * 新建机器人-表单提交
   * @param values
   */
  const onFinish = async (values: CallLimitDetailInfo) => {
    console.log('onFinish', values);
    const { dayAllowableTimes, weekAllowableTimes, monthAllowableTimes, halfYearAllowableTimes } =
      values;
    const msg = checkAllowableTimes(
      dayAllowableTimes,
      weekAllowableTimes,
      monthAllowableTimes,
      halfYearAllowableTimes
    );
    if (msg !== 'ok') {
      // 检测不通过
      message.error(msg);
      return;
    }
    setConfirmLoading(true);
    try {
      await updateCallLimitDetail({
        ...values,
      });
      successFn();
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    setConfirmLoading(false);
  };

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };
  return (
    <Modal
      className="call-limit-modal"
      title="呼叫频次设置"
      visible={visible}
      confirmLoading={confirmLoading}
      onOk={handleOK}
      onCancel={handleCancel}
    >
      <Form
        form={form}
        {...layout}
        onFinish={onFinish}
        initialValues={{
          dayAllowableTimes,
          weekAllowableTimes,
          monthAllowableTimes,
          halfYearAllowableTimes,
        }}
      >
        <p>请至少填写以下一种设置</p>
        <Form.Item name="dayAllowableTimes" label="一天内允许被呼叫次数">
          <InputNumber min={1} max={10} precision={0} placeholder="请输入1-10" />
        </Form.Item>
        <Form.Item name="weekAllowableTimes" label="一周内允许被呼叫次数">
          <InputNumber min={1} max={20} precision={0} placeholder="请输入1-20" />
        </Form.Item>
        <Form.Item name="monthAllowableTimes" label="一个月允许被呼叫次数">
          <InputNumber min={1} max={50} precision={0} placeholder="请输入1-50" />
        </Form.Item>
        <Form.Item name="halfYearAllowableTimes" label="六个月允许被呼叫次数">
          <InputNumber min={1} max={100} precision={0} placeholder="请输入1-100" />
        </Form.Item>
      </Form>
    </Modal>
  );
};
